#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@Project: kubeext-SDS 
@File: util.py
@Author: admin
@Date: 2022/6/2 14:17 
@desc: 
"""
import argparse
import os
import uuid

from utils.constant.constant import KUBESDS_LOG
from utils.cstor_util import CstorPool
from utils.exception import KubdesdsExecuteException
from utils.logger import set_logger

logger = set_logger(os.path.basename(__file__), KUBESDS_LOG)


def get_random_uuid():
    return str(uuid.uuid4()).replace('-', '')


class FooAction(argparse.Action):
    def __init__(self, option_strings, dest, nargs=None, **kwargs):
        if nargs is not None:
            raise ValueError("nargs not allowed")
        super(FooAction, self).__init__(option_strings, dest, **kwargs)

    def __call__(self, parser, namespace, values, option_string=None):
        # 当values值为None时，传递过来的实则为 'None' ，此时需额外处理一下，变成None
        values = values if values != 'None' else eval(values)
        setattr(namespace, self.dest, values)


def getArgparseParam(params):
    """
    生成命令行参数
    :param params: 命令行参数字典
    :return: 命令行参数
    """
    # 构造解析器
    parser = argparse.ArgumentParser()
    parser_str = ''
    for key, values in params.items():
        key_str = '--' + str(key)
        values_str = str(values)
        # 添加命令行参数名
        parser.add_argument(key_str, action=FooAction)
        parser_str += key_str + ' ' + values_str + ' '
    args = parser.parse_args(parser_str.split())
    return args


def get_cstor_pool(poolname):
    """
    获取cstor中存储信息
    :param poolname: 存储msid值，而非所谓的pool
    :return:
    """
    res = None
    try:
        cstor = CstorPool(poolname).pool_show()
        res = cstor['data']
    except Exception as e:
        raise KubdesdsExecuteException('kubesdsTestError', 'get cstor pool error.')
    finally:
        return res


def check_pool_info(pool_info):
    """
    检查通过cstor show-pool查询存储所得信息，主要检查存储类型和存储msid对应表cl_hostlocalstorage_inf的poolname内容
    :param pool_info:
    :return:
    """
    if pool_info.get('status') != 'active':
        raise KubdesdsExecuteException('kubesdsTestError', 'pool is not active.')
    # 存储所属类型: localfs|ipsan|nfs|glusterfs|ceph|ceph_dev
    pool_type = pool_info.get('proto')
    # 存储对应表cl_hostlocalstorage_inf的poolname内容
    pool = pool_info.get('uuid')
    if not pool_type or not pool:
        raise KubdesdsExecuteException('kubesdsTestError', 'pool type or pool is none.')
    return pool_type, pool
